package com.xzkj.ad

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.text.TextUtils
import android.view.ViewGroup
import com.google.gson.Gson
import com.ifmvo.togetherad.baidu.TogetherAdBaidu
import com.ifmvo.togetherad.core.TogetherAd
import com.ifmvo.togetherad.core.listener.BannerListener
import com.ifmvo.togetherad.core.listener.InterListener
import com.ifmvo.togetherad.core.listener.RewardListener
import com.ifmvo.togetherad.csj.TogetherAdCsj
import com.ifmvo.togetherad.gdt.TogetherAdGdt
import com.ifmvo.togetherad.ks.TogetherAdKs
import com.orhanobut.MyLog
import com.xzkj.sp.SpUtils
import java.util.LinkedHashMap

@SuppressLint("StaticFieldLeak")
object AdManager {

    var adConfigJsonBean: AdConfigJson? = null
    lateinit var context: Context


    /**
     * 尽量放在 Application 的 onCreate 方法中初始化，否则可能会影响填充率
     */
    @JvmStatic
    fun init(context: Context) {
        this.context = context
        val initConfig = InitConfig()
        val map = LinkedHashMap<String, Int>()

        val localAdJson = SpUtils.get(context, AdConst.LOCAL_AD_JSON, "")
        if (TextUtils.isEmpty(localAdJson)) {
            //说明第一次启动，使用默认的
            initConfig.csjConfig =
                BaseConfig("5217127", "887573350", "948036817", "948140216", "948036835")
            initConfig.gdtConfig = BaseConfig(
                "1200511777",
                "5013724620719254",
                "8083129786157951",
                "7043328786245955",
                "1053729736561068"
            )
            initConfig.baiduConfig =
                BaseConfig("e71abb0a", "8053642", "8059860", "8059856", "8059861")
            initConfig.ksConfig = BaseConfig()

            map[AdProviderType.CSJ.type] = 3
            map[AdProviderType.GDT.type] = 1
            map[AdProviderType.BAIDU.type] = 1
            map[AdProviderType.KS.type] = 0
            initConfig.ratioPublicMap = map
        } else {
            //说明本地已经保存了广告配置
            val adConfigJson = Gson().fromJson(localAdJson, AdConfigJson::class.java)
            adConfigJsonBean = adConfigJson

            initConfig.csjConfig = BaseConfig(
                adConfigJson.csj.appId,
                adConfigJson.csj.spId,
                adConfigJson.csj.baId,
                adConfigJson.csj.inId,
                adConfigJson.csj.reId
            )
            initConfig.gdtConfig = BaseConfig(
                adConfigJson.ylh.appId,
                adConfigJson.ylh.spId,
                adConfigJson.ylh.baId,
                adConfigJson.ylh.inId,
                adConfigJson.ylh.reId
            )
            initConfig.baiduConfig = BaseConfig(
                adConfigJson.bqt.appId,
                adConfigJson.bqt.spId,
                adConfigJson.bqt.baId,
                adConfigJson.bqt.inId,
                adConfigJson.bqt.reId
            )
            initConfig.ksConfig = BaseConfig(
                adConfigJson.ks.appId,
                adConfigJson.ks.spId,
                adConfigJson.ks.baId,
                adConfigJson.ks.inId,
                adConfigJson.ks.reId
            )

            map[AdProviderType.CSJ.type] = adConfigJson.csj.ratio
            map[AdProviderType.GDT.type] = adConfigJson.ylh.ratio
            map[AdProviderType.BAIDU.type] = adConfigJson.bqt.ratio
            map[AdProviderType.KS.type] = adConfigJson.ks.ratio
            initConfig.ratioPublicMap = map
        }
        val csjConfig = initConfig.csjConfig
        val gdtConfig = initConfig.gdtConfig
        val baiduConfig = initConfig.baiduConfig
        val ksConfig = initConfig.ksConfig

        //初始化穿山甲
        TogetherAdCsj.init(
            context = context,
            adProviderType = AdProviderType.CSJ.type,
            csjAdAppId = csjConfig.appId,
            appName = context.getString(R.string.app_name)
        )
        //初始化广点通
        TogetherAdGdt.init(
            context = context,
            adProviderType = AdProviderType.GDT.type,
            gdtAdAppId = gdtConfig.appId
        )
        //初始化百青藤
        TogetherAdBaidu.init(
            context = context,
            adProviderType = AdProviderType.BAIDU.type,
            baiduAdAppId = baiduConfig.appId
        )
        //初始化快手
        TogetherAdKs.init(
            context = context,
            adProviderType = AdProviderType.KS.type,
            ksAdAppId = ksConfig.appId
        )

        /**
         * 配置所有广告位ID
         * 如果你的ID是服务器下发，也可以把配置ID放在其他位置，但是必须要在请求广告之前完成配置，否则无法加载广告
         */
        TogetherAdCsj.idMapCsj = config2Map(csjConfig)

        TogetherAdGdt.idMapGDT = config2Map(gdtConfig)

        TogetherAdKs.idMapKs = mutableMapOf(
            TogetherAdAlias.AD_SPLASH to ksConfig.spId.toLong(),
            TogetherAdAlias.AD_REWARD to ksConfig.reId.toLong(),
            TogetherAdAlias.AD_BANNER to ksConfig.baId.toLong(),
            TogetherAdAlias.AD_INTER to ksConfig.inId.toLong()
        )

        TogetherAdBaidu.idMapBaidu = config2Map(baiduConfig)

        val ratioPublicMap = initConfig.ratioPublicMap
        if (!ratioPublicMap.isNullOrEmpty()) {
            TogetherAd.setPublicProviderRatio(ratioPublicMap)
        }
    }

    /**
     * 保存所有广告配置数据。包含比例，各个广告位的id，还有总开关
     * @param context Context
     * @param adConfigJson String 加密的字符串
     */
    fun setAdConfig(context: Context, adConfigJson: String) {
        try {
            val extendJsonStr = SecretUtil.decodeBase64AndDecryptAES(adConfigJson)
            MyLog.e("配置表》》》》" + extendJsonStr)
            SpUtils.put(context, AdConst.LOCAL_AD_JSON, extendJsonStr)
            val adConfigBean = Gson().fromJson(extendJsonStr, AdConfigJson::class.java)
            adConfigJsonBean = adConfigBean

            SpUtils.put(context, AdConst.SPLASH_AD_NUM, 0)
        } catch (e: Exception) {

        }
    }

    /**
     * 服务器接口请求失败次数。用来判断是否加载开屏广告。如果>=2就加载开屏广告。
     */
    fun setSplashADNum(context: Context) {
        try {
            var splashADNum = SpUtils.get(context, AdConst.SPLASH_AD_NUM, 0)
            splashADNum++
            SpUtils.put(context, AdConst.SPLASH_AD_NUM, splashADNum)
        } catch (e: Exception) {

        }
    }

    /**
     * 服务器接口请求失败次数。用来判断是否加载开屏广告。如果》=2就加载开屏广告。
     */
    fun getSplashADNum(context: Context): Int {
        return SpUtils.get(context, AdConst.SPLASH_AD_NUM, 0)
    }

    private fun config2Map(baseConfig: BaseConfig): MutableMap<String, String> {
        return mutableMapOf(
            TogetherAdAlias.AD_SPLASH to baseConfig.spId,
            TogetherAdAlias.AD_REWARD to baseConfig.reId,
            TogetherAdAlias.AD_BANNER to baseConfig.baId,
            TogetherAdAlias.AD_INTER to baseConfig.inId
        )
    }

    fun loadSplashAD(
        activity: Activity,
        adContainer: ViewGroup,
        mainActClass: Class<out Activity>
    ) {
        SplashAd.show(activity, adContainer, mainActClass)
    }

    fun loadBannerAD(activity: Activity, adContainer: ViewGroup, listener: BannerListener? = null) {
        if (adConfigJsonBean?.adSw == 0) {
            return
        }
        BannerAd.show(activity, adContainer, listener)
    }

    fun loadRewardAD(activity: Activity, listener: RewardListener? = null) {
        if (adConfigJsonBean?.adSw == 0) {
            return
        }
        RewardAd.loadAndShow(activity, listener)
    }

    fun loadInterAD(activity: Activity, listener: InterListener? = null) {
        if (adConfigJsonBean?.adSw == 0) {
            return
        }
        InterAd.loadAndShow(activity, listener)
    }


}